"""Setup the ciby-net application"""
import logging

from paste.deploy import appconfig
from pylons import config

from cibynet.config.environment import load_environment
from cibynet.utils import populate_db

#import code
#import inspect
#import readline, rlcompleter
#readline.parse_and_bind("tab: complete")
#code.interact(local=inspect.currentframe().f_locals)

# Here we automatically import the model modules to populate the metadata.
import dircache
import re
reg = re.compile("^m_.+\.py$")
l =  dircache.listdir("cibynet/model/")
l = [m[:-3] for m in l if reg.match(m)]
__import__("cibynet.model", fromlist=l)
del l
del reg

log = logging.getLogger(__name__)


def setup_config(command, filename, section, vars):
    """Place any commands to setup cibynet here"""
    conf = appconfig('config:' + filename)
    load_environment(conf.global_conf, conf.local_conf)
    
    from cibynet.model import meta
    log.info("Creating tables")
    
    meta.metadata.drop_all(bind=meta.engine)
    meta.metadata.create_all(bind=meta.engine)
    log.info("Successfully setup")

    if filename.endswith("production.ini"):
      log.info("Populate DB for prod from old one.")
      populate_db.PopulateDBWithAdminAndSuperAdmin(meta.engine)
      populate_db.PopulateDBForProd(meta.engine)
    else:
      log.info("Inserting initial data")
      populate_db.PopulateDBForTests(meta.engine)
      
    log.info("Done")